<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
           v-allow="'import_excel'"
            @click="$router.push('/import')"
            type="warning"
            size="small"
            >excel导入</el-button
          >
          <el-button v-allow="'export_excel'" @click="exportexcel" type="danger" size="small"
            >excel导出</el-button
          >
          <el-button v-allow="'add'" @click="showDialog = true" type="primary" size="small"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'correctionTime', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" prop="username">
            <template #default="{ row }" width="100">
              <img
                @click="showCode(row.staffPhoto)"
                :src="row.staffPhoto"
                style="width: 100%"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{ formData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="correctionTime" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <!-- 查询参数传值 -->
              <el-button
                @click="$router.push(`/employees/detail?userId=${row.id}`)"
                type="text"
                size="small"
                >查看</el-button
              >
              <el-button @click="hAssignRole(row.id)" type="text" size="small"
                >分配角色</el-button
              >
              <el-button @click="hDel(row.id)" type="text" size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="size"
            layout=" prev, pager, next"
            :total="total"
          >
          </el-pagination>
        </el-row>
      </el-card>
      <!-- 新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addDialog @success="hSuccess" @close="hClose" />
      </el-dialog>
      <!-- 点击头像生成二维码弹层 -->
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog title="分配角色" :visible.sync="showassignRole">
        <assignRole v-if="showassignRole" @close="showassignRole=false" :curId="curId" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { delEmployees, getEmployees } from "@/api/imployees";
import employeesEnum from "@/constant/employees";
import addDialog from "./employeeDialog.vue";
import QrCode from "qrcode";
import assignRole from "./assignRole.vue";
export default {
  components: {
    addDialog,
    assignRole,
  },
  data() {
    return {
      curId: "",
      showassignRole: false,
      showCodeDialog: false,
      showDialog: false,
      page: 1,
      size: 5,
      total: 0,
      list: [],
    };
  },
  created() {
    this.loadEmployees();
  },
  methods: {
    //分配角色弹层
    hAssignRole(id) {
      this.curId=id
      this.showassignRole=true
    },
    //生成二维码
    showCode(url) {
      this.showCodeDialog = true;
      this.$nextTick(() => {
        const canvas = this.$refs.myCanvas;
        QrCode.toCanvas(canvas, url);
      });
    },
    //导出excel功能
    exportexcel() {
      import("@/vendor/Export2Excel").then((excel) => {
        const { tHeader, data } = this.transZhKeyToExcel(this.list);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType,
        });
      });
    },
    //实现中文转英文生成表头和内容
    transZhKeyToExcel(list) {
      const mapInfo = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };
      //1.生成表头
      const one = list[0];
      if (!one) return;
      const tHeader = Object.keys(one).map((enkey) => {
        return mapInfo[enkey];
      });
      const data = list.map((item) => {
        return Object.values(item);
      });
      return { tHeader, data };
    },
    //删除功能
    hDel(id) {
      this.$confirm("确定要删除此角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delEmployees(id);
          if (res.code !== 10000) return this.$message.error(res.message);
          this.$message.success(res.message);
          if (this.list.length === 1) {
            this.page--;
            if (this.page <= 0) {
              this.page = 1;
            }
          }
          this.loadEmployees();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.loadEmployees();
    },
    hSuccess() {
      this.total++;
      const maxPage = Math.ceil(this.total / this.size);
      this.page = maxPage;
      this.loadEmployees();
      this.showDialog = false;
    },
    //取消关闭弹层
    hClose() {
      this.showDialog = false;
    },
    //格式化枚举
    formData(id) {
      const hireType = {};
      employeesEnum.hireType.forEach(
        (item) => (hireType[item.id] = item.value)
      );
      return hireType[id];
    },
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size });
        // console.log("getEmployees", res);
        if (res.code !== 10000) return this.$message.error(res.message);
        this.$message.success(res.message);
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (err) {
        console.log("getEmployees", err);
      }
    },
  },
};
</script>